// var async=require('async');
// var User=require('../models/userModel.js');
// var JpScore=require('../models/jpScoreModel.js');

// var redisClient=require('../connections/clientConnection.js');
// var uuid=require('node-uuid');
//
// var path=require('path');
//
// var zancun = require('./zancun');
var hfc = require('fabric-client');
var path = require('path');
var sdkUtils = require('fabric-client/lib/utils')
var fs = require('fs');
var util = require('util');

module.exports={
	testyuansheng:function(req,res,next){
		console.log(typeof req.body);
		console.log(req.body);
		var data = req.body ;
		// JpScore
		// .find()
		// .then(function(doc){
		// 	if(doc[0].jpScore <= parseInt(data.score)){
		// 		doc[0].jpScore = parseInt(data.score) ;
		// 	};
		// 	res.send({
		// 		jpScore:doc[0].jpScore
		// 	});
		// },function(err){
		// 	if(err) console.log(err);
		// });//JpScore
		console.log('arrive1');
		if(zancun.jpScore<=parseInt(data.score)){
			zancun.jpScore=parseInt(data.score);
			console.log('arrive2');
		};//
		console.log('arrive3');
		var t = JSON.stringify({"jpScore":zancun.jpScore});
			console.log(t);
		res.send(t);

		next();
	},//Testyuansheng

	GetHtml:function(req,res,next){
		// console.log(req.sessionID);
		// res.render('index', {errorMessage:''},function(err,html){
		res.render('index', {},function(err,html){
			if(err)console.log(err);
			res.send(html);
		});
	},

	RegisterHtml:function(req,res,next){
		////////////////////////////////////////////////////////////
        var A = null ;
        var B = null ;

		console.log(1)
        var options = {
            user_id: 'Admin@org1.example.com',
            msp_id:'Org1MSP',
            channel_id: 'mychannel',
            chaincode_id: 'mychannel',
            network_url: 'grpc://localhost:7051',//因为启用了TLS，所以是grpcs,如果没有启用TLS，那么就是grpc
            privateKeyFolder:'/hp/blockchain/nodeTest',
            signedCert:'/hp/blockchain/nodeTest/Admin@org1.example.com-cert.pem',
            tls_cacerts:'/hp/blockchain/nodeTest/ca.crt',
            server_hostname: "peer0.org1.example.com"
        };

        var channel = {};
        var client = null;
        const getKeyFilesInDir = (dir) => {
//该函数用于找到keystore目录下的私钥文件的路径
            var files = fs.readdirSync(dir)
            var keyFiles = []
            files.forEach((file_name) => {
                let filePath = path.join(dir, file_name)
                if (file_name.endsWith('_sk')) {
                keyFiles.push(filePath)
            }
        })
            return keyFiles
        }
        Promise.resolve().then(() => {
            console.log("Load privateKey and signedCert");
        client = new hfc();
        var    createUserOpt = {
            username: options.user_id,
            mspid: options.msp_id,
            cryptoContent: { privateKey: getKeyFilesInDir(options.privateKeyFolder)[0],
                signedCert: options.signedCert }
        }
//以上代码指定了当前用户的私钥，证书等基本信息
        return sdkUtils.newKeyValueStore({
            path: "/tmp/fabric-client-stateStore/"
        }).then((store) => {
            client.setStateStore(store)
        return client.createUser(createUserOpt)
    })
    }).then((user) => {
            channel = client.newChannel(options.channel_id);

        let data = fs.readFileSync(options.tls_cacerts);
        let peer = client.newPeer(options.network_url,
            {
                pem: Buffer.from(data).toString(),
                'ssl-target-name-override': options.server_hostname
            }
        );
        peer.setName("peer0");
//因为启用了TLS，所以上面的代码就是指定TLS的CA证书
        channel.addPeer(peer);
        return;
    }).then(() => {
            console.log("Make query");
        var transaction_id = client.newTransactionID();
        console.log("Assigning transaction_id: ", transaction_id._transaction_id);
//构造查询request参数
        const request = {
            chaincodeId: options.chaincode_id,
            txId: transaction_id,
            fcn: 'query',
            args: ['A']
        };
        return channel.queryByChaincode(request);
    }).then((query_responses) => {
            console.log("returned from query");
        if (!query_responses.length) {
            console.log("No payloads were returned from query");
        } else {
            console.log("Query result count = ", query_responses.length)
        }
        if (query_responses[0] instanceof Error) {
            console.error("error from query = ", query_responses[0]);
        }
        console.log("Response is ", query_responses[0].toString());//打印返回的结果
        A = query_responses[0].toString() ;
		// res.send({"result":query_responses[0].toString()});
        //////////////////////////////////////////////////////////////////
        var channel = {};
        var client = null;
        const getKeyFilesInDir = (dir) => {
//该函数用于找到keystore目录下的私钥文件的路径
            var files = fs.readdirSync(dir)
            var keyFiles = []
            files.forEach((file_name) => {
                let filePath = path.join(dir, file_name)
                if (file_name.endsWith('_sk')) {
                keyFiles.push(filePath)
            }
        })
            return keyFiles
        }
        Promise.resolve().then(() => {
            console.log("Load privateKey and signedCert");
        client = new hfc();
        var    createUserOpt = {
            username: options.user_id,
            mspid: options.msp_id,
            cryptoContent: { privateKey: getKeyFilesInDir(options.privateKeyFolder)[0],
                signedCert: options.signedCert }
        }
//以上代码指定了当前用户的私钥，证书等基本信息
        return sdkUtils.newKeyValueStore({
            path: "/tmp/fabric-client-stateStore/"
        }).then((store) => {
            client.setStateStore(store)
        return client.createUser(createUserOpt)
    })
    }).then((user) => {
            channel = client.newChannel(options.channel_id);

        let data = fs.readFileSync(options.tls_cacerts);
        let peer = client.newPeer(options.network_url,
            {
                pem: Buffer.from(data).toString(),
                'ssl-target-name-override': options.server_hostname
            }
        );
        peer.setName("peer0");
//因为启用了TLS，所以上面的代码就是指定TLS的CA证书
        channel.addPeer(peer);
        return;
    }).then(() => {
            console.log("Make query");
        var transaction_id = client.newTransactionID();
        console.log("Assigning transaction_id: ", transaction_id._transaction_id);
//构造查询request参数
        const request = {
            chaincodeId: options.chaincode_id,
            txId: transaction_id,
            fcn: 'query',
            args: ['B']
        };
        return channel.queryByChaincode(request);
    }).then((query_responses) => {
            console.log("returned from query");
        if (!query_responses.length) {
            console.log("No payloads were returned from query");
        } else {
            console.log("Query result count = ", query_responses.length)
        }
        if (query_responses[0] instanceof Error) {
            console.error("error from query = ", query_responses[0]);
        }
        console.log("Response is2 ", query_responses[0].toString());//打印返回的结果
        B = query_responses[0].toString() ;
        res.send({result : [A,B]});
    }).catch((err) => {
            console.error("Caught Error", err);
    });
        //////////////////////////////////////////////////////////////////
    }).catch((err) => {
            console.error("Caught Error", err);
    });
		////////////////////////////////////////////////////////////
	},

	ArrangeClassesHtml:function(req,res,next){
		console.log("ready for transmitting");
        var options = {
            user_id: 'Admin@org1.example.com',
            msp_id:'Org1MSP',
            channel_id: 'mychannel',
            chaincode_id: 'mychannel',
            peer_url: 'grpc://localhost:7051',//因为启用了TLS，所以是grpcs,如果没有启用TLS，那么就是grpc
            event_url: 'grpc://localhost:7053',//因为启用了TLS，所以是grpcs,如果没有启用TLS，那么就是grpc
            orderer_url: 'grpc://localhost:7050',//因为启用了TLS，所以是grpcs,如果没有启用TLS，那么就是grpc
            privateKeyFolder:'/hp/blockchain/nodeTest',
            signedCert:'/hp/blockchain/nodeTest/Admin@org1.example.com-cert.pem',
            peer_tls_cacerts:'/hp/blockchain/nodeTest/crypto-config/peerOrganizations/org1.example.com/peers/peer0.org1.example.com/tls/ca.crt',
            orderer_tls_cacerts:'/hp/blockchain/nodeTest/crypto-config/ordererOrganizations/example.com/orderers/orderer.example.com/tls/ca.crt',
            server_hostname: "peer0.org1.example.com"
        };

        var channel = {};
        var client = null;
        var targets = [];
        var tx_id = null;
        const getKeyFilesInDir = (dir) => {
//该函数用于找到keystore目录下的私钥文件的路径
            const files = fs.readdirSync(dir)
            const keyFiles = []
            files.forEach((file_name) => {
                let filePath = path.join(dir, file_name)
                if (file_name.endsWith('_sk')) {
                keyFiles.push(filePath)
            }
        })
            return keyFiles
        }
        Promise.resolve().then(() => {
            console.log("Load privateKey and signedCert");
        client = new hfc();
        var    createUserOpt = {
            username: options.user_id,
            mspid: options.msp_id,
            cryptoContent: { privateKey: getKeyFilesInDir(options.privateKeyFolder)[0],
                signedCert: options.signedCert }
        }
//以上代码指定了当前用户的私钥，证书等基本信息
        return sdkUtils.newKeyValueStore({
            path: "/tmp/fabric-client-stateStore/"
        }).then((store) => {
            client.setStateStore(store)
        return client.createUser(createUserOpt)
    })
    }).then((user) => {
            channel = client.newChannel(options.channel_id);
        let data = fs.readFileSync(options.peer_tls_cacerts);
        let peer = client.newPeer(options.peer_url,
            {
                pem: Buffer.from(data).toString(),
                'ssl-target-name-override': options.server_hostname
            }
        );
//因为启用了TLS，所以上面的代码就是指定Peer的TLS的CA证书
        channel.addPeer(peer);
//接下来连接Orderer的时候也启用了TLS，也是同样的处理方法
        let odata = fs.readFileSync(options.orderer_tls_cacerts);
        let caroots = Buffer.from(odata).toString();
        var orderer = client.newOrderer(options.orderer_url, {
            'pem': caroots,
            'ssl-target-name-override': "orderer.example.com"
        });

        channel.addOrderer(orderer);
        targets.push(peer);
        return;
    }).then(() => {
            tx_id = client.newTransactionID();
        console.log("Assigning transaction_id: ", tx_id._transaction_id);
//发起转账行为，将a->b 10元
        var request = {
            targets: targets,
            chaincodeId: options.chaincode_id,
            fcn: 'invoke',
            args: ['A', 'B', '1'],
            chainId: options.channel_id,
            txId: tx_id
        };
        return channel.sendTransactionProposal(request);
    }).then((results) => {
        var proposalResponses = results[0];
        var proposal = results[1];
        var header = results[2];
        let isProposalGood = false;
        if (proposalResponses && proposalResponses[0].response &&
            proposalResponses[0].response.status === 200) {
            isProposalGood = true;
            console.log('transaction proposal was good');
        } else {
            console.error('transaction proposal was bad');
        }
        if (isProposalGood) {
            console.log(util.format(
                'Successfully sent Proposal and received ProposalResponse: Status - %s, message - "%s", metadata - "%s", endorsement signature: %s',
                proposalResponses[0].response.status, proposalResponses[0].response.message,
                proposalResponses[0].response.payload, proposalResponses[0].endorsement.signature));
            var request = {
                proposalResponses: proposalResponses,
                proposal: proposal,
                header: header
            };
            // set the transaction listener and set a timeout of 30sec
            // if the transaction did not get committed within the timeout period,
            // fail the test
            var transactionID = tx_id.getTransactionID();
            var eventPromises = [];
            let eh = client.newEventHub();
            //接下来设置EventHub，用于监听Transaction是否成功写入，这里也是启用了TLS
            let data = fs.readFileSync(options.peer_tls_cacerts);
            let grpcOpts = {
                pem: Buffer.from(data).toString(),
                'ssl-target-name-override': options.server_hostname
            }
            eh.setPeerAddr(options.event_url,grpcOpts);
            eh.connect();

            let txPromise = new Promise((resolve, reject) => {
                let handle = setTimeout(() => {
                    eh.disconnect();
            reject();
        }, 30000);
//向EventHub注册事件的处理办法
            eh.registerTxEvent(transactionID, (tx, code) => {
                clearTimeout(handle);
            eh.unregisterTxEvent(transactionID);
            eh.disconnect();

            if (code !== 'VALID') {
                console.error(
                    'The transaction was invalid, code = ' + code);
                reject();
            } else {
                console.log(
                    'The transaction has been committed on peer ' +
                    eh._ep._endpoint.addr);
                resolve();
            }
        });
        });
            eventPromises.push(txPromise);
            var sendPromise = channel.sendTransaction(request);
            return Promise.all([sendPromise].concat(eventPromises)).then((results) => {
                console.log(' event promise all complete and testing complete');
            return results[0]; // the first returned value is from the 'sendPromise' which is from the 'sendTransaction()' call
        }).catch((err) => {
                console.error(
                'Failed to send transaction and get notifications within the timeout period.'
            );
            return 'Failed to send transaction and get notifications within the timeout period.';
        });
        } else {
            console.error(
                'Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...'
            );
            return 'Failed to send Proposal or receive valid response. Response null or status is not 200. exiting...';
        }
    }, (err) => {
            console.error('Failed to send proposal due to error: ' + err.stack ? err.stack :
                err);
            return 'Failed to send proposal due to error: ' + err.stack ? err.stack :
                err;
        }).then((response) => {
            if (response.status === 'SUCCESS') {
            console.log('Successfully sent transaction to the orderer.');
            res.send({"result":tx_id._transaction_id});
            // return tx_id.getTransactionID();    // 这条可以加上
        } else {
            console.error('Failed to order the transaction. Error code: ' + response.status);
            return 'Failed to order the transaction. Error code: ' + response.status;
        }
    }, (err) => {
            console.error('Failed to send transaction due to error: ' + err.stack ? err
                .stack : err);
            return 'Failed to send transaction due to error: ' + err.stack ? err.stack :
                err;
        });

	},

	Login:function(req,res,next){
        var options = {
            user_id: 'Admin@org1.example.com',
            msp_id:'Org1MSP',
            channel_id: 'mychannel',
            chaincode_id: 'mychannel',
            network_url: 'grpc://localhost:7051',//因为启用了TLS，所以是grpcs,如果没有启用TLS，那么就是grpc
            privateKeyFolder:'/hp/blockchain/nodeTest',
            signedCert:'/hp/blockchain/nodeTest/Admin@org1.example.com-cert.pem',
            tls_cacerts:'/hp/blockchain/nodeTest/ca.crt',
            server_hostname: "peer0.org1.example.com"
        };

        var channel = {};
        var client = null;
        const getKeyFilesInDir = (dir) => {
//该函数用于找到keystore目录下的私钥文件的路径
            var files = fs.readdirSync(dir)
            var keyFiles = []
            files.forEach((file_name) => {
                let filePath = path.join(dir, file_name)
                if (file_name.endsWith('_sk')) {
                keyFiles.push(filePath)
            }
        })
            return keyFiles
        }
        Promise.resolve().then(() => {
            console.log("Load privateKey and signedCert");
        client = new hfc();
        var    createUserOpt = {
            username: options.user_id,
            mspid: options.msp_id,
            cryptoContent: { privateKey: getKeyFilesInDir(options.privateKeyFolder)[0],
                signedCert: options.signedCert }
        }
//以上代码指定了当前用户的私钥，证书等基本信息
        return sdkUtils.newKeyValueStore({
            path: "/tmp/fabric-client-stateStore/"
        }).then((store) => {
            client.setStateStore(store)
        return client.createUser(createUserOpt)
    })
    }).then((user) => {
            channel = client.newChannel(options.channel_id);

        let data = fs.readFileSync(options.tls_cacerts);
        let peer = client.newPeer(options.network_url,
            {
                pem: Buffer.from(data).toString(),
                'ssl-target-name-override': options.server_hostname
            }
        );
        peer.setName("peer0");
//因为启用了TLS，所以上面的代码就是指定TLS的CA证书
        channel.addPeer(peer);
        return;
    }).then(() => {
            console.log("Make query");
        var transaction_id = client.newTransactionID();
        console.log("Assigning transaction_id: ", transaction_id._transaction_id);
//构造查询request参数
        const request = {
            chaincodeId: options.chaincode_id,
            txId: transaction_id,
            fcn: 'query',
            args: ['A']
        };
        return channel.queryTransaction("af2d9ddaf45b6b1cae1947bf9ec6b8e44d2dcebe035fcca738f576139c521fdd");
    }).then((query_responses) => {
            console.log("returned from queryTransaction");
        console.log(query_responses.validationCode);
        console.log(query_responses.transactionEnvelope);
        res.send({result:query_responses});
// if (!query_responses.length) {
//     console.log("No payloads were returned from query");
// } else {
//     console.log("Query result count = ", query_responses.length)
// }
// if (query_responses[0] instanceof Error) {
//     console.error("error from query = ", query_responses[0]);
// }
// console.log("Response array is ", query_responses);
// console.log("Response is ", query_responses[0].toString());//打印返回的结果
    }).catch((err) => {
            console.error("Caught Error", err);
    });
	},
    queryBlockByTransactionid : function(req,res,next){
	    var transactionId = req.body.transactionId ;
	    console.log(transactionId);
        var options = {
            user_id: 'Admin@org1.example.com',
            msp_id:'Org1MSP',
            channel_id: 'mychannel',
            chaincode_id: 'mychannel',
            network_url: 'grpc://localhost:7051',//因为启用了TLS，所以是grpcs,如果没有启用TLS，那么就是grpc
            privateKeyFolder:'/hp/blockchain/nodeTest',
            signedCert:'/hp/blockchain/nodeTest/Admin@org1.example.com-cert.pem',
            tls_cacerts:'/hp/blockchain/nodeTest/ca.crt',
            server_hostname: "peer0.org1.example.com"
        };

        var channel = {};
        var client = null;
        const getKeyFilesInDir = (dir) => {
//该函数用于找到keystore目录下的私钥文件的路径
            var files = fs.readdirSync(dir)
            var keyFiles = []
            files.forEach((file_name) => {
                let filePath = path.join(dir, file_name)
                if (file_name.endsWith('_sk')) {
                keyFiles.push(filePath)
            }
        })
            return keyFiles
        }
        Promise.resolve().then(() => {
            console.log("Load privateKey and signedCert");
        client = new hfc();
        var    createUserOpt = {
            username: options.user_id,
            mspid: options.msp_id,
            cryptoContent: { privateKey: getKeyFilesInDir(options.privateKeyFolder)[0],
                signedCert: options.signedCert }
        }
//以上代码指定了当前用户的私钥，证书等基本信息
        return sdkUtils.newKeyValueStore({
            path: "/tmp/fabric-client-stateStore/"
        }).then((store) => {
            client.setStateStore(store)
        return client.createUser(createUserOpt)
    })
    }).then((user) => {
            channel = client.newChannel(options.channel_id);

        let data = fs.readFileSync(options.tls_cacerts);
        let peer = client.newPeer(options.network_url,
            {
                pem: Buffer.from(data).toString(),
                'ssl-target-name-override': options.server_hostname
            }
        );
        peer.setName("peer0");
//因为启用了TLS，所以上面的代码就是指定TLS的CA证书
        channel.addPeer(peer);
        return;
    }).then(() => {
            console.log("Make query");
        var transaction_id = client.newTransactionID();
        console.log("Assigning transaction_id: ", transaction_id._transaction_id);
//构造查询request参数
        const request = {
            chaincodeId: options.chaincode_id,
            txId: transaction_id,
            fcn: 'query',
            args: ['A']
        };
        // return channel.queryBlockByTxID("af2d9ddaf45b6b1cae1947bf9ec6b8e44d2dcebe035fcca738f576139c521fdd");
        // return channel.queryBlockByTxID("a0a1e5f2157bf25d05cf31422f52758bc94a882d337222b93d2962217b139512");
        console.log(transactionId);
        return channel.queryBlockByTxID(transactionId);

    }).then((query_responses) => {
        console.log("returned from query");
        console.log(query_responses);
        res.send({"result":query_responses});

// if (!query_responses.length) {
//     console.log("No payloads were returned from query");
// } else {
//     console.log("Query result count = ", query_responses.length)
// }
// if (query_responses[0] instanceof Error) {
//     console.error("error from query = ", query_responses[0]);
// }
// console.log("Response is ", query_responses[0].toString());//打印返回的结果
    }).catch((err) => {
            console.error("Caught Error", err);
    });

    },
    queryMultiproperty : function(req,res,next){
        /////////////////////////////////////////////////////////////
        var options = {
            user_id: 'Admin@org1.example.com',
            msp_id:'Org1MSP',
            channel_id: 'mychannel',
            chaincode_id: 'carcc3',
            network_url: 'grpc://localhost:7051',//因为启用了TLS，所以是grpcs,如果没有启用TLS，那么就是grpc
            privateKeyFolder:'/hp/blockchain/nodeTest',
            signedCert:'/hp/blockchain/nodeTest/Admin@org1.example.com-cert.pem',
            tls_cacerts:'/hp/blockchain/nodeTest/ca.crt',
            server_hostname: "peer0.org1.example.com"
        };

        var channel = {};
        var client = null;
        const getKeyFilesInDir = (dir) => {
//该函数用于找到keystore目录下的私钥文件的路径
            var files = fs.readdirSync(dir)
            var keyFiles = []
            files.forEach((file_name) => {
                let filePath = path.join(dir, file_name)
                if (file_name.endsWith('_sk')) {
                keyFiles.push(filePath)
            }
        })
            return keyFiles
        }
        Promise.resolve().then(() => {
            console.log("Load privateKey and signedCert");
        client = new hfc();
        var    createUserOpt = {
            username: options.user_id,
            mspid: options.msp_id,
            cryptoContent: { privateKey: getKeyFilesInDir(options.privateKeyFolder)[0],
                signedCert: options.signedCert }
        }
//以上代码指定了当前用户的私钥，证书等基本信息
        return sdkUtils.newKeyValueStore({
            path: "/tmp/fabric-client-stateStore/"
        }).then((store) => {
            client.setStateStore(store)
        return client.createUser(createUserOpt)
    })
    }).then((user) => {
            channel = client.newChannel(options.channel_id);

        let data = fs.readFileSync(options.tls_cacerts);
        let peer = client.newPeer(options.network_url,
            {
                pem: Buffer.from(data).toString(),
                'ssl-target-name-override': options.server_hostname
            }
        );
        peer.setName("peer0");
//因为启用了TLS，所以上面的代码就是指定TLS的CA证书
        channel.addPeer(peer);
        return;
    }).then(() => {
            console.log("Make query");
        var transaction_id = client.newTransactionID();
        console.log("Assigning transaction_id: ", transaction_id._transaction_id);
//构造查询request参数
        const request = {
            chaincodeId: options.chaincode_id,
            txId: transaction_id,
            fcn: 'queryPost',
            args: ['POST1']
        };
        return channel.queryByChaincode(request);
    }).then((query_responses) => {
            console.log("returned from query");
        if (!query_responses.length) {
            console.log("No payloads were returned from query");
        } else {
            console.log("Query result count = ", query_responses.length)
        }
        if (query_responses[0] instanceof Error) {
            console.error("error from query = ", query_responses[0]);
        }
        console.log("Response is ", query_responses.toString());//打印返回的结果
        res.send({result:query_responses.toString()});
    }).catch((err) => {
            console.error("Caught Error", err);
    });
        /////////////////////////////////////////////////////////////
    },
	LoginApp:function(req,res){
			//验证账号
		var data=req.body,
		username=data.username,
		password=data.password;
		//数据库部分
		User
		.find({username:username})
		.then(function(doc){
			console.log(doc);
			if(doc.length==0) {
					res.send({
						code:[1001,'不存在用户']
					});
			};
			if(doc[0].password===password){
				if(!req.session.token){
					req.session.token=uuid.v1();
				}
					res.send({
						code:[1000,'登陆成功'],
						// data:doc[0]
					})
				}else{
					res.send({
						code:[1001,'不存在用户'],
						// data:doc[0]
					});
				}
			}
			,function(err){
				console.log(err);
			}
		);
	},//LoginApp
	Logout:function(req,res){
		delete req.session.token;
		res.render('index',{errorMessage:''});
	},
	NotepadGet:function(req,res){
		
	}
}